package com.opo5.logisticsmanagement.controller;

import com.alibaba.fastjson.JSONObject;
import com.opo5.logisticsmanagement.common.R;
import com.opo5.logisticsmanagement.common.streamToJson;
import com.opo5.logisticsmanagement.domain.User;
import com.opo5.logisticsmanagement.service.loginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("userLogin")
@ResponseBody
public class loginController {
    @Autowired
    private loginService loginService;
    @PostMapping

    public R<Object> login(HttpServletRequest request) throws IOException {
        User user = new User();
        R<Object> r;
        JSONObject result = streamToJson.toJson(request.getReader());
        if (result != null){
            user.setNickname(result.getString("nickname"));
            user.setPassword(result.getString("password"));
        }
        if (user.getNickname()!=null && !user.getNickname().equals("")) {
            r = loginService.login(user);
            if (r.getCode()==200){
                Map<String, String> sessionInfoMap = new HashMap<>();
                String sessionId = request.getSession().getId();
                String requestURI = request.getRequestURI() + ":"  +  request.getServerPort();
                request.getSession().setAttribute("nickname",result.getString("nickname"));
                request.getSession().setAttribute("user_role",r.getMap().get("user_role"));
                sessionInfoMap.put("sessionId", sessionId);
                sessionInfoMap.put("requestURI", requestURI);
                sessionInfoMap.put("userinfo", result.getString("nickname"));
                r.setMap(sessionInfoMap);
            }
        }else{
            r = new R<>();
            r.setCode(500);
            r.setMsg("账号或密码格式错误");
        }
        return r;
    }
    @GetMapping
    public R<Object> logout (HttpServletRequest request){
        R<Object> r = new R<>();
        request.getSession().removeAttribute("nickname");
        r.setCode(200);
        r.setMsg("OK");
        return r;
    }
}
